#include "TableBlackList.h"
CTableBlackList::CTableBlackList()
{
  env = Environment::createEnvironment(Environment::DEFAULT);
  conn = env->createConnection("liu","liu","XE");
  stmt = conn->createStatement();
}
CTableBlackList::~CTableBlackList()
{
  if(NULL != stmt)
  {
    conn->terminateStatement(stmt);
  }
  env->terminateConnection(conn);
  Environment::terminateEnvironment(env);
}

int32_t CTableBlackList::checkblack(const char* phone, const char* check)
{
  TPhoneList blacklist;
  memset(&blacklist, '\0', sizeof(blacklist));
  this->get_item(phone, blacklist);

  for(int j = 0; j<blacklist.m_nNum;j++)
  {
    int ret =  strcmp((char*)blacklist.m_list[j], check);
    if (ret == 0)
    {
      return 1;
    }
  }
  return 0;
}

int32_t CTableBlackList::get_item(const char* phone,TPhoneList& blacklist)
{
  int ret = 0;
  ret = get_local(phone, blacklist);
  if (-1 == ret)
  {
    ret = get_oracle(phone, blacklist);
  }
  return ret;
}

int32_t CTableBlackList::get_oracle(const char* phone,TPhoneList& blacklist)
{
  char strSQL[512] = {0};
  snprintf(strSQL, 512, "%s", "SELECT black FROM t_black_list WHERE phone = :1");
	ResultSet *rs = NULL;
  int i = 0;
	try
	{
    stmt->setSQL(strSQL);
    stmt->setString(1, phone);
		rs = stmt->executeQuery();
    if (NULL != rs)
    {
      while(rs->next())
      {
        string s1= rs->getString(1);
        strncpy((char*)blacklist.m_list[i] , s1.c_str(), s1.size());
        i++;
        blacklist.m_nNum = i;
      }
    }
		stmt->closeResultSet(rs);
	}
	catch(SQLException e)
	{
		if (NULL != rs)
		{
			stmt->closeResultSet(rs);
		}
		cout<<"SQLException catched:"<<e.what()<<endl;
	}
  if (i!= 0)
  {
    insert_local(phone, blacklist);
  }
  return 0;
}

int32_t CTableBlackList::get_local(const char* phone, TPhoneList& blacklist)
{
  return m_kv->Get(phone, &blacklist, sizeof(TPhoneList)); 
}

int32_t CTableBlackList::insert_local(const char* phone, TPhoneList& blacklist)
{
  return m_kv->Put(phone, &blacklist, sizeof(TPhoneList));
}
